package cn.tedu._04weibo.base.exception;

import cn.tedu._04weibo.base.response.JsonResult;
import cn.tedu._04weibo.base.response.StatusCode;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * ControllerAdvice注解:
 *   1.标识该类为全局异常处理器;
 *   2.当控制器抛出异常时,框架优先检查是否定义了全局异常处理器;
 * RestControllerAdvice注解:
 *   1.组合注解,相当于:ControllerAdvice + ResponseBody注解;
 *   2.添加该注解后,所有的异常处理方法上无需再添加 @ResponseBody 注解;
 */

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult doHandlerMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        String data = ex.getFieldError().getDefaultMessage();
        log.error(" MethodArgumentNotValidException = "+data);
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }
    @ExceptionHandler
    public JsonResult doHandlerConstraintViolationException(ConstraintViolationException ex){
        String data = ex.getMessage().split(":")[1].trim();
        log.error(" ConstraintViolationException = "+data);
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }

}
